/**
 * 
 */
package ro.dta.idbi.patterns.primitives;

import java.util.EnumSet;

import ro.dta.idbi.interfaces.IntegrationOperation;
import ro.dta.idbi.model.AbstractPrimitivePattern;
import uk.ac.ic.doc.automed.IntegrityException;
import uk.ac.ic.doc.automed.NotFoundException;
import uk.ac.ic.doc.automed.reps.Schema;
import uk.ac.ic.doc.automed.reps.SchemaObject;
import uk.ac.ic.doc.automed.reps.TypeMismatchException;

/**
 * <b>Primitive transformation to contract a SQL construct</b><br />
 * 
 * Example of use:<br />
 * 
 * <code>contract (table:&lt;&lt;tableName&gt;&gt;, Range ql qu)</code><br />
 * <code>contract (column:&lt;&lt;tableName,columnName,optionality,type&gt;&gt;, Range ql qu)</code>
 * <br />
 * 
 * @author Tudor Dobrila
 * 
 */
public class ContractPrimitive extends AbstractPrimitivePattern {

	/**
	 * Name of the pattern
	 */
	public static final String NAME = "Contract construct";

	/**
	 * Description of the pattern
	 */
	public static final String DESCRIPTION = "Contract existing construct";

	/**
	 * Name of the command associated with the pattern
	 */
	public static final String COMMAND = "contract";

	/**
	 * Integration phase during which the command is applied
	 */
	public static final EnumSet<IntegrationOperation> OPERATION = EnumSet.of(
			IntegrationOperation.CONFORMING, IntegrationOperation.MERGING,
			IntegrationOperation.IMPROVEMENT);
	
	/**
	 * Contract existing construct class constructor
	 * 
	 * @param sourceSchema
	 *            Source schema over which the transformation is applied
	 */
	public ContractPrimitive(final Schema sourceSchema) throws NotFoundException, IntegrityException {
		super(sourceSchema, COMMAND);
	}

	/**
	 * Contract existing construct class constructor
	 * 
	 * @param sourceSchema
	 *            Name of source schema over which the transformation is applied
	 */
	public ContractPrimitive(final String sourceSchema) throws NotFoundException, IntegrityException {
		this(Schema.getSchema(sourceSchema));
	}
	
	@Override
	public Schema execute(String trans) throws NotFoundException, TypeMismatchException,
			IntegrityException {
		super.execute(trans);

		Schema crtSchema = sourceSchema;
		String type = (String) construct.get("type");
		SchemaObject contrObj = null;
		String extent = null;
		
		if ("table".equals(type)) {
			String name = (String) construct.get("name");
			extent = (String) construct.get("iql");
			contrObj = sourceSchema.getSchemaObject("<<" + name + ">>");
		} else if ("column".equals(type)) {
			String table = (String) construct.get("table");
			String name = (String) construct.get("name");
			extent = (String) construct.get("iql");
			contrObj = crtSchema.getSchemaObject("<<" + table + "," + name + ">>");
		}
		
		if (contrObj != null) {
			crtSchema = crtSchema.applyContractTransformation(contrObj, extent, null);
		}

		return crtSchema;
	}
}
